#!/bin/bash
set -eu

root=$(cd $(dirname $0)/.. && pwd)

# First we have to remove the instrumented folder, so when we compile the typescript again
# it won't try to compile these files
cd $root

rm -rf __instrumented__
mkdir -p __instrumented__

# Compile the typescript
echo "Compiling Typescript..."

echo "Instrumenting code..."
npx nyc instrument --compact=false static/js __instrumented__/ts

# We need to use the instrumented code when running cypress
mv static/js/appbundle.js static/js/appbundle_orig.js

npx esbuild ./__instrumented__/ts \
    --bundle \
    --sourcemap \
    --target=es2017 \
    --global-name=hedyApp \
    --platform=browser \
    --outfile=static/js/appbundle.js "$@"

echo "Running cypress tests..."
cd tests
# The ! means that even if the tests fail, the script won't exit. Instead it'll continue it's execution and clean the
# files generated during the script. You can understand this as a way to override -e just in this line. More info here:
# https://stackoverflow.com/questions/47261313/whats-the-meaning-of-a-before-a-command-in-the-shell

! npx cypress run

rm -rf ../static/js/appbundle.js
rm -rf ../__instrumented__

mv ../static/js/appbundle_orig.js ../static/js/appbundle.js

echo "Done! You can check the coverage now!"
